---
title: "Foreign interference - Google Trends"
author: "Mathieu Lavigne"
date: "2026-04-07"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Set working directory and load packages

```{r}
# Set working directory
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

# Load packages (remove # and run first line if pacman package not already installed)
# install.packages("pacman")

pacman::p_load(tidyverse, scales, ggrepel)
```

## Load Google Trends data

```{r}
# Load data
trends <- read_csv("./fig_d7_foreign_interference_trends.csv", skip=2)
```

## Recode variables

```{r}
trends <- trends %>% 
  # Remove character symbols
  mutate(`interference china: (Canada)` = ifelse(`interference china: (Canada)` %in% 0:100, `interference china: (Canada)`, 0),
  # Put variable in numeric format
         `interference china: (Canada)` = as.numeric(`interference china: (Canada)`)) %>% 
  # Put data in long format
  pivot_longer(-Semaine, names_to="Keywords", values_to = "Interest") %>% 
  rename(Date=Semaine) %>% 
  # Create factor variable
  mutate(Keywords = factor(Keywords, levels=c("foreign interference: (Canada)", "election interference: (Canada)", "chinese interference: (Canada)", "interference china: (Canada)")))
```

## Create and save Figure D7

```{r}
# Create figure
fig_d7 <- ggplot(trends, aes(x=Date, y=Interest, col=Keywords, linetype=Keywords))+
  geom_line(size=0.7)+
   annotate("text", x=as.Date("2021-09-21"), y=max(trends$Interest, na.rm = TRUE)-10, 
           label="2021 election", vjust=-0.5, hjust=-0.05, size=3.5) +
  geom_vline(xintercept=as.Date("2021-09-21"), linetype="dashed")+
  scale_x_date(breaks = "1 year", labels=date_format("%Y")) +
  scale_color_viridis_d()+
  theme_minimal()

# Save figure
ggsave(fig_d7, file="./Figures/Figure_D7_foreign_interference_trends.png", bg="white", height=4)
```

